import matplotlib.pyplot as plt
from wordcloud import WordCloud
from imageio import imread
from scanfiles import scan_files
import csv


def create_cloud(dic):
    # 将内容写入temp.txt
    with open('temp.txt', 'w', encoding='utf-8') as f:
        for i in dic:
            f.write(("%s " % i[0]) * i[1] + "\n")
    temp_txt = open("temp.txt", "r", encoding='utf-8').read()
    filepath = 'cloudshape'
    scan_files(filepath)        # 扫描词云图背景图文件
    cloudshape = filepath + '\\' + "bird.jpg"   # 默认背景图片

    # 选择词云图背景文件的序号
    picture_no = input("Please select a background by the number in range:")
    with open('filename.csv', 'r', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for i in reader:
            if picture_no == i[0]:
                print('You choose cloud shape:', i[1], end='\n')
                cloudshape = filepath + '\\' + i[1]
        if cloudshape == filepath + '\\' + "bird.jpg":  # 判断是否成功选择词云形状
            print('Input error,use default cloud shape bird.jpg', end='\n')

    color_mask = imread(cloudshape)  # 词云形状图设置

    # 词云参数设置
    cloud = WordCloud(
        font_path='C:\\Windows\\Fonts\\simfang.ttf',  # 字体必须设置
        background_color='white',  # 词云图像的背景色，默认为黑色
        mask=color_mask,  # 绘制模板
        max_words=200,  # 最大显示单词字数
        max_font_size=200,  # 最大单词的字体大小，若无设置，则使用画布的大小
    )
    word_cloud = cloud.generate(temp_txt)
    plt.imshow(word_cloud)
    plt.axis('off')
    plt.show()
